﻿package com.sorayume.script {
	
	import flash.events.EventDispatcher;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	
	import com.sorayume.core.SY_Event;
	import com.sorayume.script.SY_Chapter;
	
	public class SY_Script extends EventDispatcher {
		
		private var _isLoaded:Boolean = false;
		private var _isExec:Boolean = false;
		private var _currentFile:String = "";
		
		private var _currentChapter:SY_Chapter = null;
		private var _currentChapter_len:int = 0;
		private var _currentChapter_ptr:int = 0;
		
		private var _xml:XML = null;
		
		private var _puppetIds:Array = new Array();
		private var _puppetHnd:Array = new Array();
		
		private var _meta_version:String = "";
		private var _meta_description:String = "";
		private var _meta_firstChapter:String = "";
		private var _meta_assets:XMLList = null;
		
		private var _chapter_index:Array = new Array();
		private var _chapters:Array = new Array();
		
		public function SY_Script() {
			// constructor code
		}
		
		public function loadXML(filename:String):void
		{
			if (!_isLoaded) {
				var ldrXml = new URLLoader(new URLRequest(filename));
				ldrXml.addEventListener(Event.COMPLETE, hndXmlLoaded);
				ldrXml.addEventListener(IOErrorEvent.IO_ERROR, hndXmlError);
				_currentFile = filename;
			} else {
				oops("Ya se ha cargado el XML " + _currentFile + "en este objeto.");
			}
		}
		private function hndXmlError(evt:IOErrorEvent):void 
		{
			evt.target.removeEventListener(IOErrorEvent.IO_ERROR, hndXmlError);
			evt.target.removeEventListener(Event.COMPLETE, hndXmlLoaded);
			
			oops("No se encontró el XML.");
		}
		private function hndXmlLoaded(evt:Event):void
		{
			evt.target.removeEventListener(Event.COMPLETE, hndXmlLoaded);
			evt.target.removeEventListener(IOErrorEvent.IO_ERROR, hndXmlError);
			_xml = XML(evt.target.data);
			_isLoaded = true;
			
			setMeta();
			createChapters();
			
			_currentChapter = this.getChapter(_meta_firstChapter);
			_currentChapter_len = _currentChapter.length();
			_currentChapter_ptr = 0;
			
			this.dispatchEvent(new SY_Event(SY_Event.ON_XML_LOADED));
		}
		
		private function setMeta():void 
		{
			_meta_version = String(_xml.meta.version);
			_meta_description = String(_xml.meta.description);
			_meta_firstChapter = String(_xml.meta.firstchapter);
			_meta_assets = _xml.meta.assets;
		}
		private function createChapters():void 
		{
			var tmpChap:SY_Chapter = null;
			for each(var chapter:XML in _xml.story.chapter) {
				tmpChap = new SY_Chapter(chapter.@id, chapter.*);
				_chapter_index.push(String(chapter.@id));
				_chapters.push(tmpChap);
			}
		}
		
		public function beginExec():void
		{
			if (_isLoaded) {
				if (!_isExec) {
					_isExec = true;
					
				} else {
					oops("Ya está ejecutándose");
				}
			} else {
				oops("No hay XML cargado.");
			}
		}
		
		public function execThis(command:XML):int
		{
			var cmdName:String = String(command.name());
			switch (cmdName) 
			{
				case "text":
					world_text(String(command.@caption), String(command));
					return 0;
				break;
				case "background":
					world_background(command.@scr);
					return 0;
				break;
				case "puppet":
					if (_puppetIds.indexOf(String(command.@id)) === -1) {
						var graphicHnd = world_puppet(command.@src, command.@pos);
						_puppetIds.push(String(command.@id));
						_puppetHnd.push(String(graphicHnd));
						return 0;
					} else {
						return -1;
					}
				break;
				case "setpuppet":
					if (_puppetIds.indexOf(String(command.@who)) === -1) {
						
					} else {
						return -1
					}
				break;
				case "choice":
					
				break;
				case "detour":
					
				break;
				case "end":
					
				break;
				default:
					oops("Comando no válido");
					return -1;
				break;
			}
			return -1;
		}
				
		private function oops(description:String):void 
		{
			this.dispatchEvent(new SY_Event(SY_Event.ON_ERROR, {desc: description}));
		}
		
		public function getChapter(id:String):* 
		{
			var index:int = _chapter_index.indexOf(id);
			if (index === -1) { return false; }
			
			return _chapters[index];
		}
		
		public function getVersion():*
		{
			if (_isLoaded) {
				return _meta_version;
			} else {
				oops("No hay XML cargado.");
				return false;
			}
		}
		public function getDescription():*
		{
			if (_isLoaded) {
				return _meta_description;
			} else {
				oops("No hay XML cargado.");
				return false;
			}
		}
		public function getFirstChapeterId():*
		{
			if (_isLoaded) {
				return _meta_firstChapter;
			} else {
				oops("No hay XML cargado.");
				return false;
			}
		}
		public function getCurrentChapter():*
		{
			return _currentChapter;
		}
		public function getCurrentChapterId():*
		{
			if (_isLoaded) {
				return _currentChapter.id();
			} else {
				oops("No hay XML cargado.");
				return false;
			}
		}
		
		public function isPlaying():Boolean
		{
			return _isExec;
		}
		
		public function getXML():*
		{
			if (_isLoaded) {
				return _xml;
			} else {
				oops("No hay XML cargado.");
				return false;
			}
		}
		
		/* --------------------------------- Llamadas a WORLD ------------------------------------------------*/
		
		private function world_text(caption:String, content:String):void 
		{
			trace("TEXT: caption="+caption+", content"+content);
		}
		private function world_background(assetId:String):void 
		{
			trace("BACKGROUND: assetId=" + assetId);
		}
		
		private function world_puppet(assetId:String, position:String):int 
		{
			trace("PUPPET: assetId=" + assetId + ", position=" + position);
			return Math.random() * 100;
		}
		
	}
	
}